package com.shaozi.nc.data.mongodao;

import java.util.List;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import com.shaozi.data.mongo.dao.SZMongoBaseDao;
import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.MqApiQuartzModel;

@Repository("secretaryApiQuartzMDao")
public class SecretaryApiQuartzMDao extends SZMongoBaseDao<MqApiQuartzModel> {

	@Autowired
	public SecretaryApiQuartzMDao(MongoTemplate shaoziTemplate) {
		super(shaoziTemplate);
	}

	public void save(String companyId, MqApiQuartzModel model) throws SzException {
		if (model.getCreateTime() == null) {
			model.setCreateTime(System.currentTimeMillis());
		}
		model.setUpdateTime(System.currentTimeMillis());
		if (model.getIsDel() == null) {
			model.setIsDel(0);
			model.setDelTime(null);
		}
		model.setCompanyId(companyId);

		getMongoTemplate().save(model, getCollectionName(companyId));
	}

	public List<MqApiQuartzModel> getBySource(String companyId, Integer sourceId, int sourceType, String triggerUserId)
			throws SzException {
		if (sourceId == null)
			return null;
		Criteria c = new Criteria("triggerUserId").is(triggerUserId);
		c.and("sourceId").is(sourceId).and("sourceType").is(sourceType);
		c.and("isDel").is(0);
		Query query = new Query(c);
		return getMongoTemplate().find(query, MqApiQuartzModel.class, getCollectionName(companyId));
	}

	public void delModel(String companyId, String _id, int delType) throws SzException {
		Criteria c = new Criteria("_id").is(new ObjectId(_id));
		c.and("isDel").is(0);
		Update update = new Update();
		update.set("isDel", 1);
		update.set("delType", delType);
		update.set("delTime", System.currentTimeMillis());
		update.set("updateTime", System.currentTimeMillis());
		getMongoTemplate().updateFirst(new Query(c), update, MqApiQuartzModel.class, getCollectionName(companyId));
	}

	public List<MqApiQuartzModel> listAll(String companyId) throws SzException {
		Criteria c = new Criteria("isDel").is(0);
		Query query = new Query(c);
		return getMongoTemplate().find(query, MqApiQuartzModel.class, getCollectionName(companyId));
	}

	public MqApiQuartzModel getById(String companyId, String _id) throws SzException {
		Criteria c = new Criteria("_id").is(new ObjectId(_id));
		Query query = new Query(c);
		return getMongoTemplate().findOne(query, MqApiQuartzModel.class, getCollectionName(companyId));
	}

}
